package task

import (
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	"log"
	"my_gin_blog/models"
	"sync"
)

func GenerateExcel() {
	log.Println("Start")
	currentMonthData, err := models.GetCurrentMonthData(1559983663, 1566118063)
	if err != nil {
		log.Fatalf("Failed to get data: %v", err)
	}

	file := excelize.NewFile()
	log.Printf("Total records to process: %d", len(currentMonthData))

	headers := []string{"次序", "编号Id", "编号"}
	for col, header := range headers {
		cell := excelize.ToAlphaString(col+1) + "1"
		file.SetCellValue("Sheet1", cell, header)
	}
	log.Println("Start generating")

	var wg sync.WaitGroup
	var mutex sync.Mutex

	// 创建一个 channel 用于接收写入 Excel 的请求
	writeChannel := make(chan struct {
		row  int
		data models.BigQueryLogDetail
	})

	// 启动单独的 goroutine 进行文件写入
	go func() {
		for {
			select {
			case request, ok := <-writeChannel:
				if !ok {
					// 关闭 writeChannel 后退出循环
					return
				}

				// 使用更细粒度的锁，确保对 Excel 文件的写入操作是线程安全的
				mutex.Lock()
				file.SetCellValue("Sheet1", "A"+fmt.Sprint(request.row), request.row)
				file.SetCellValue("Sheet1", "B"+fmt.Sprint(request.row), request.data.SoNumberId)
				file.SetCellValue("Sheet1", "C"+fmt.Sprint(request.row), request.data.SoNumber)
				//file.SetCellValue("Sheet1", "D"+fmt.Sprint(request.row), request.data.SendBqTime.Format("2006-01-02 15:04:05"))
				mutex.Unlock()
			}
		}
	}()

	for i, data := range currentMonthData {
		wg.Add(1)
		go func(row int, d models.BigQueryLogDetail) {
			defer wg.Done()

			// 将写入请求发送到 channel
			writeChannel <- struct {
				row  int
				data models.BigQueryLogDetail
			}{row: row + 1, data: d}
		}(i, data)
	}

	// 等待所有写入 goroutine 完成
	wg.Wait()

	// 关闭 writeChannel，通知文件写入 goroutine 停止
	close(writeChannel)

	// Save the Excel file
	outputFileName := "output223311.xlsx"
	mutex.Lock()
	err = file.SaveAs(outputFileName)
	mutex.Unlock()

	if err != nil {
		log.Fatalf("Failed to save Excel file (%s): %v", outputFileName, err)
	}
	log.Println("End")
}
